<template>
  <div>
    <UseBreadcrumb>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </UseBreadcrumb>
    <el-card class="box-card">
      <el-alert
        title="注意:只允许给第三级分类设置相关参数!"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <el-tag type="info">选择商品类别:</el-tag>
          <!--商品类别级联菜单  -->
          <el-cascader
            clearable
            v-model="selectedCategoryId"
            :options="goodsList"
            :props="selectedCategory"
            @change="selectedCate"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 页签区域 -->
      <el-tabs v-model="tabActiveName" @tab-click="tabHandleClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many" size="mini">
          <el-button
          class="addbtn"
            type="primary"
            :disabled="!btnIsDisabled"
            @click="showAddParamsDialog"
            >添加参数</el-button
          >
          <!-- 动态参数表格  -->
          <el-table border stripe :data="activeGoodsParams" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="item,i of scope.row.attr_vals"
                  :key="item"
                  @close="tagClose(scope.row,i)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.tagInputVisible"
                  v-model.trim="tagInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only" size="mini">
          <el-button
            type="primary"
            :disabled="!btnIsDisabled"
            @click="showAddParamsDialog"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table border stripe :data="staticGoodsParams" style="width: 100%">
              <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="item,i of scope.row.attr_vals"
                  :key="item"
                  @close="tagClose(scope.row,i)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.tagInputVisible"
                  v-model.trim="tagInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"> </el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      @close="addParamsDialogClose"
      :title="'添加' + paramsDialogtitle"
      :visible.sync="addParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="paramsDialogtitle" prop="attr_name">
          <el-input type="text" v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      @close="editParamsDialogClose"
      :title="'修改' + paramsDialogtitle"
      :visible.sync="editParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="paramsDialogtitle" prop="attr_name">
          <el-input type="text" v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import UseBreadcrumb from '@/common_components/UseBreadcrumb'
export default {
  data() {
    return {
      goodsList: [],
      selectedCategory: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      //选中类别的Id
      selectedCategoryId: [],
      //选中的页签
      tabActiveName: 'many',
      //动态参数数据
      activeGoodsParams: [],
      //静态属性数据
      staticGoodsParams: [],
      //添加参数对话框的显示/隐藏
      addParamsDialogVisible: false,
      paramsDialogtitle: '',
      //添加参数表单信息对象
      addForm: {
        attr_name: '',
      },
      //添加参数表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //修改参数对话框的显示/隐藏
      editParamsDialogVisible: false,
      //修改参数表单信息对象
      editForm: {
        attr_name: '',
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      //new tag标签的值
      tagInputValue: '',
    }
  },
  components: {
    UseBreadcrumb,
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      let {
        data: { data: res, meta },
      } = await this.$api.getCategoryData()
      if (meta.status === 200) {
        this.goodsList = res
      }
    },
    //监听商品级联菜单选中事件
    async selectedCate() {
      //默认只可以选中三级菜单
      if (this.selectedCategoryId.length !== 3) {
        this.selectedCategoryId = []
        this.activeGoodsParams = []
        this.staticGoodsParams = []
        return
      }
      //根据选中类别的Id和选中面板的tabActiveName值来发起请求
      this.getGoodsParamsData()
    },
    //监听页签点击事件
    tabHandleClick() {
      this.getGoodsParamsData()
    },
    //获取商品参数数据
    async getGoodsParamsData() {
      let {
        data: { data: res, meta },
      } = await this.$api.getGoodsData(this.selectedCategoryId[2], {
        params: { sel: this.tabActiveName },
      })
        res.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            //给参数的attr_vals添加个布尔值,实现每个属性控制自己的tag标签的切换
            item.tagInputVisible = false
          })
      if (meta.status === 200) {
        if (this.tabActiveName === 'many') {
          this.activeGoodsParams = res
          this.paramsDialogtitle = '动态参数'
        } else if (this.tabActiveName === 'only') {
          
          this.staticGoodsParams = res
          this.paramsDialogtitle = '静态属性'
        }
      } else {
        this.$message.error('获取数据失败,请先选择商品类别')
      }
    },
    //展示添加参数对话框
    showAddParamsDialog() {
      this.addParamsDialogVisible = true
    },
    //添加参数对话框关闭,重置表单
    addParamsDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    //添加参数请求
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        let {
          data: { _, meta },
        } = await this.$api.addGoodsParams(this.selectedCategoryId[2], {
          attr_name: this.addForm.attr_name,
          attr_sel: this.tabActiveName,
        })
        if (meta.status === 201) {
          this.$message.success('添加成功')
          this.getGoodsParamsData()
          this.addParamsDialogVisible = false
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    //监听修改参数对话框的关闭,
    editParamsDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    //展示修改数据对话框
    async showEditParamsDialog(attrId) {
      let {
        data: { data: res, meta },
      } = await this.$api.getOneParams(this.selectedCategoryId[2], attrId, {
        params: { attr_sel: this.tabActiveName },
      })
      if (meta.status === 200) {
        this.editForm = res
      }
      this.editParamsDialogVisible = true
    },
    //点击按钮,实现修改参数功能
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        let { data: res } = await this.$api.editGoodsParams(
          this.selectedCategoryId[2],
          this.editForm.attr_id,
          { attr_name: this.editForm.attr_name, attr_sel: this.tabActiveName }
        )
        if (res.meta.status === 200) {
          this.$message.success('修改成功')
          this.getGoodsParamsData()
          this.editParamsDialogVisible = false
        } else {
          this.$message.error('修改失败')
        }
      })
    },
    //点击删除按钮,删除商品参数
    async removeParams(attrId) {
      let res = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (res === 'confirm') {
        let {
          data: { _, meta },
        } = await this.$api.deleteGoodsParams(
          this.selectedCategoryId[0],
          attrId
        )
        if (meta.status === 200) {
          this.getGoodsParamsData()
          this.$message.success('删除参数成功')
        }
      } else {
        this.$message.info('已取消删除')
      }
    },
    //保存对tag标签中商品参数属性的操作
    async saveTag(rowVal) {
      let {
        data: { _, meta },
      } = await this.$api.addGoodsParamsAttr(
        this.selectedCategoryId[2],
        rowVal.attr_id,
        {
          attr_name: rowVal.attr_name,
          attr_sel: rowVal.attr_sel,
          attr_vals: rowVal.attr_vals.join(' '),
        }
      )
      if (meta.status !== 200) {
        return this.$message.error('操作失败')
      }else{
        this.$message.success('操作成功')
      }
    },
    //tag标签失焦,添加新属性
    handleInputConfirm(rowVal) {
      let val = this.tagInputValue
      if (val) {
        rowVal.attr_vals.push(val)
        this.saveTag(rowVal)
      }
      rowVal.tagInputVisible = false
      this.tagInputValue = ''
    },
    showInput(rowVal) {
      //tagInputVisible改为true后,页面的DOM不是改为true的DOM，vue渲染DOM是异步的
      rowVal.tagInputVisible = true
      //nextTick方法是页面渲染完毕后,可以获取渲染完的真实DOM
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    tagClose(rowVal,i) {
      rowVal.attr_vals.splice(i,1)
      this.saveTag(rowVal)
    },
  },
  computed: {
    btnIsDisabled() {
      return this.selectedCategoryId.slice().length === 3
    },
  },
}
</script>

<style lang="less" scoped>
.el-row {
  margin-top: 10px;
  .el-col {
    height: 42px;
    line-height: 42px;
    .el-tag {
      height: 40px;
      line-height: 40px;
      font-size: 13px;
      margin-right: 5px;
    }
  }
}
.el-table {
  .el-tag {
    margin-right: 5px;
  }
  .input-new-tag {
    width: 150px;
  }
}
.addbtn {
  margin-bottom: 10px;
}

</style>
